package cn.kooki.app.duobao.ui.Fragment;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseFragment;
import cn.kooki.app.duobao.base.BaseRecyclerAdapter;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.Result.LortteryResponse;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Goods.GoodsDetailAcitvity;
import cn.kooki.app.duobao.ui.Adapter.ResultAdapter;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.ui.widget.XRecylerView;
import cn.kooki.app.duobao.util.manager.CountDownTimerManager;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/11/25.
 */
public class NewLotteryFragment extends BaseFragment {


    @Bind(R.id.top_back)
    ImageButton topBack;
    @Bind(R.id.top_text_center)
    TextView topTextCenter;
    @Bind(R.id.top_refresh)
    ImageButton topRefresh;
    @Bind(R.id.top_cart)
    ImageButton topCart;
    @Bind(R.id.action_edit)
    TextView actionEdit;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;

    @Bind(R.id.loadingWrapper)
    CustomRelativeLayout loadingWrapper;
    @Bind(R.id.recycelerView)
    XRecylerView recycelerView;
    private boolean ishasData = false;
    private ResultAdapter adapter;
    private CountDownTimerManager manager;
    private long lasttime = 0;
    private int page = 1;

    @Override
    public View setView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_result, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void afterView() {

        topTextCenter.setText(R.string.tab_result);
        topTextCenter.setVisibility(View.VISIBLE);
        GridLayoutManager gridLayoutManager = getGridLayoutManager(2);
        recycelerView.setLayoutManager(gridLayoutManager);
        adapter = new ResultAdapter();
        recycelerView.setAdapter(adapter);
        if (adapter != null) {
            adapter.startObservable();
        }
        loadingWrapper.setRetryClickListener(new CustomRelativeLayout.onRetryClickListener() {
            @Override
            public void onRetry() {
                loadingWrapper.hideNetError();
                recycelerView.autoRefresh(false);
            }
        });
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                GoodsItem item = (GoodsItem) data;
                HashMap<String, String> parmas = new HashMap<>();
                parmas.put("id", item.getId());
                parmas.put("qishu", item.getQishu());
                intent(GoodsDetailAcitvity.class, parmas);
            }
        });

        recycelerView.setLoadingMoreEnabled(true);
        recycelerView.setLoadingListener(new XRecylerView.LoadingListener() {
            @Override
            public void onRefresh() {
                lasttime = System.currentTimeMillis();
                getdata(false);
            }

            @Override
            public void onLoadMore() {
                getdata(true);
            }
        });
    }


    private void getdata(final boolean isloadmore) {

        if (isloadmore) {
            page++;
        } else {
            page = 1;
        }

        MainFactory.getApiInstance().listresult(page, new Callback<LortteryResponse>() {
            @Override
            public void success(LortteryResponse lortteryResponse, Response response) {

                if (lortteryResponse.data != null) {
                    if (!isloadmore) {
                        adapter.mDatas.clear();
                    }

                    CountDownTimerManager.getInstance().clearTimers();
                    adapter.addDatas(lortteryResponse.data);
                    CountDownTimerManager.getInstance().setDatas(adapter.mDatas);
                    CountDownTimerManager.getInstance().startCountDown();

                    if (lortteryResponse.data.size() == Constants.DEFAULT_COUNT) {
                        recycelerView.restMoreLoading();
                    } else {
                        recycelerView.noMoreLoading();
                    }
                }
                if (isloadmore) {
                    recycelerView.loadMoreComplete();
                } else {
                    recycelerView.restMoreLoading();
                    hideloading();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (error.getKind() == RetrofitError.Kind.NETWORK) {
                    loadingWrapper.showNetError();
                }
                if (isloadmore) {
                    recycelerView.loadMoreComplete();
                } else {
                    hideloading();
                }
            }
        });
    }

    private void hideloading() {
        loadingWrapper.hideloading();
        recycelerView.refreshComplete();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - lasttime > 1000 * 60 * 1000) {
                if (recycelerView != null) {
                    recycelerView.autoRefresh(false);

                }

            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (adapter != null) {
            adapter.stopObservable();
        }
        ButterKnife.unbind(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }
}
